/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package emailpoller;

import java.util.ArrayList;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;

/**
 *
 * @author Arttu
 */
public class EmailPollerTask extends Task<ObservableList<String>> implements EMailPollerListener {

    private ReadOnlyObjectWrapper<ObservableList<String>> partialResults = new ReadOnlyObjectWrapper<>(this, "partialResults", FXCollections.observableArrayList(new ArrayList()));
    private SimpleEMailPoller poller;
    
    public EmailPollerTask(SimpleEMailPoller poller) {
        this.poller = poller;
        this.poller.addListener(this);
    }
    
    public final ObservableList<String> getPartialResults() {
        return partialResults.get();
    }
    
    public final ReadOnlyObjectProperty getPartialResultsProperty() {
        return partialResults.getReadOnlyProperty();
    }
    
    @Override
    protected ObservableList<String> call() throws Exception {

        if(!poller.polling) 
            poller.startPolling();
        
        return partialResults.get();
    }

    @Override
    public void gotMessage(String message) {
        Platform.runLater(() -> {
            partialResults.get().add(message);
        });
    }

    
}
